<template>
  <div class="panel-table">
    <rj-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      :scroll="{ x: 1500 }"
      @refeshTable="refeshTable"
      :filtercolumns="true"
      bordered
      @change="handleTableDetailChange"
    >
      <div slot="customBlock" class="form-proup">
        <a-space size="middle">
          <a-input
            :maxLength="19"
            v-model="taskId"
            v-if="upgradeJobId"
            :placeholder="$t('upgradeLog.taskID')"
            @change="inputJobIdChange"
          />
          <a-input placeholder="SN" @change="inputSnChange" />
          <a-input
            :placeholder="$t('groupOperate.netname')"
            @change="inputGroupNameChange"
          />
          <a-button type="primary" icon="search" @click="inquireDetail">
            {{ $t('public.search') }}
          </a-button>
        </a-space>
      </div>
      <div slot="filterDropdown" slot-scope="{ confirm, column }">
        <div class="statuStyle">
          <a-radio-group
            :value="strChangeVariable(column, 'value')"
            @change="onChange($event, confirm)"
            v-for="(item, index) in strChangeVariable(column, 'filters')"
            :key="index"
          >
            <a-radio :value="item.confEvent">
              {{ item.desc }}
            </a-radio>
          </a-radio-group>
        </div>
      </div>
      <a-icon slot="filterIcon" type="filter" />
      <template slot="status" slot-scope="text, record">
        <span
          :class="[record.statusOld.replace(/\s/g, '').toLocaleLowerCase()]"
          >{{ text }}</span
        >
      </template>
      <template slot="statusDesc" slot-scope="text">
        <div v-html="text"></div>
      </template>
      <template slot="version" slot-scope="text, record">
        <span>{{ record.preVersion }}</span
        ><br />
        <span>{{ record.targetVersion }}</span>
      </template>
      <template slot="time" slot-scope="text, record">
        <span>{{ record.startTime }}</span
        ><br />
        <span>{{ record.endTime }}</span>
      </template>
      <template slot="operate" slot-scope="text, record">
        <a-space>
          <a-popconfirm
            :title="$t('upgradeLog.confirmStopExe')"
            :ok-text="$t('upgradeLog.ok')"
            :cancel-text="$t('upgradeLog.canel')"
            @confirm="confirmAbort(record)"
          >
            <!-- <icon-font type="ic-termination" title="停止" /> -->
            <a>{{ $t('upgradeLog.stopUpgrade') }}</a>
          </a-popconfirm>
          <a-popconfirm
            :title="$t('upgradeLog.isReExec')"
            :ok-text="$t('upgradeLog.ok')"
            :cancel-text="$t('upgradeLog.canel')"
            @confirm="confirmRestart(record)"
          >
            <!-- <icon-font type="ic-redo" title="重试" /> -->
            <a>{{ $t('upgradeLog.retry') }}</a>
          </a-popconfirm>
        </a-space>
      </template>
    </rj-table>
  </div>
</template>

<script>
import { requestHttp, maccApi } from '@utils/index';
import { RjTable } from '@components';
import { detailcolumns, statusfilters } from '../columns/columns.js';
import moment from 'moment';
export default {
  props: {
    jobid: {
      type: String,
      default: '',
    },
    upgradeJobId: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      statusvalue: '',
      // statusfilters,
      // columns: detailcolumns,
      loading: false,
      timer: null,
      data: [],
      current: 1,
      pagination: {},
      detailparams: {
        job_id: this.jobid,
        page: 1,
        per_page: 10,
        status: '',
        sn: '',
      },
      executeJobs: [],
      taskId: '',
    };
  },
  watch: {
    // 语种变化，表内文字需要同步切换
    columns() {
      this.getLogDetailList();
    },
  },
  components: {
    'rj-table': RjTable,
  },
  computed: {
    statusMap() {
      const map = { 'AUTO UPGRADE': this.$t('upgradeLog.autoUpgradeSuccess') };
      for (const key in this.statusfilters) {
        if (this.statusfilters[key].confEvent) {
          map[this.statusfilters[key].confEvent] = this.statusfilters[key].desc;
        }
      }
      return map;
    },
    columns() {
      detailcolumns.forEach((item) => {
        if (item.dataIndex1 == 'groupName') {
          return;
        }
        item.title = this.$t(`upgradeLog.${item.dataIndex1}`);
      });
      return detailcolumns;
    },
    statusfilters() {
      statusfilters.forEach((item) => {
        item.desc = this.$t(`upgradeLog.${item.i18nIndex}`);
      });
      return statusfilters;
    },
  },
  created() {
    //注册分组变更事件
    this.$iframeMsg('REGISTER_COMTED', {
      eventName: 'UPGRADE_PROGRESS_CHANGE',
      comtedCallback: (data) => {
        //console.log('=====升级进度', data);
        const logId = data.upgradeLogId;
        if (this.executeJobs.indexOf(logId) > -1) {
          console.log('设备升级日志===========', data);
          this.setTableUpgradeProgess(data);
        }
      },
    });
  },
  mounted() {
    this.getLogDetailList();
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    //设备升级日志列表
    async getLogDetailList() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.data = [];
      this.pagination = { total: 0 };
      this.loading = true;
      let url = this.callDetailLogurl();
      const res = await requestHttp({
        api: `${maccApi.JOB_LOG_GET_API}${url}`,
        method: 'GET',
      });
      if (res.code != 0) {
        this.$message.error(
          res.msg || this.$t('upgradeLog.getDeviceUpgradeLogFailed')
        );
        return;
      }
      if (res.totalCount && res.totalCount > 0) {
        let page = {
          current: this.current,
          total: res.totalCount,
          showSizeChanger: true,
          showQuickJumper: true,
        };
        this.pagination = page;
        let arr = [];
        let executeJobs = [];
        for (const key in res.logDetailList) {
          if (
            res.logDetailList[key].status == 'EXECUTING' &&
            res.logDetailList[key].executingStatus == 'EXECUTING'
          ) {
            executeJobs.push(res.logDetailList[key].id);
          }
          let obj = {};
          let start = '';
          let end = '';
          obj.key = key;
          obj.id = res.logDetailList[key].id;
          obj.upgradeJobId = res.logDetailList[key].upgradeJobId;
          obj.deviceSn = res.logDetailList[key].deviceSn;
          obj.status = this.LogDetailUpshot(res.logDetailList[key].status);
          obj.statusOld = res.logDetailList[key].status;
          obj.statusDesc = res.logDetailList[key].statusDesc;
          obj.groupName = res.logDetailList[key].groupName;
          if (res.logDetailList[key].diagnoseDesc == '') {
            obj.diagnoseDesc = '--';
          } else {
            obj.diagnoseDesc = res.logDetailList[key].diagnoseDesc;
          }
          obj.preVersion = `${this.$t(
            'upgradeLog.lastVersion'
          )}${this.getVersion(res.logDetailList[key].preVersion)}`;
          obj.targetVersion = `${this.$t(
            'upgradeLog.aimVersion'
          )}${this.getVersion(res.logDetailList[key].targetVersion)}`;
          obj.retryTimes = res.logDetailList[key].retryTimes;
          if (Object.hasOwnProperty.call(res.logDetailList[key], 'startTime')) {
            start = this.getSpecifiedTime(res.logDetailList[key].startTime);
          } else {
            start = '--';
          }
          if (
            Object.hasOwnProperty.call(res.logDetailList[key], 'finishTime')
          ) {
            end = this.getSpecifiedTime(res.logDetailList[key].finishTime);
          } else {
            end = '--';
          }
          obj.startTime = `${this.$t('upgradeLog.beginTime')}${start}`;
          obj.endTime = `${this.$t('upgradeLog.endTime')}${end}`;

          arr.push(obj);
        }
        this.data = arr;
        this.loading = false;
        this.executeJobs = executeJobs;
        // if (this.executeJobs.length > 0) {
        //   this.timer = setInterval(() => {
        //     this.getUpgradeProgress();
        //   }, 5 * 1000);
        // }
      } else {
        this.loading = false;
        this.data = [];
        this.pagination = { total: 0 };
      }
    },
    /**
     * @description: 获取当前页面正在执行得设备得升级进度
     * @param {*}
     * @return {*}
     */
    async getUpgradeProgress() {
      const res = await requestHttp({
        api: `${maccApi.JOB_LOG_UPGRADEPROGESS_POST_API}`,
        method: 'POST',
        params: this.executeJobs,
      });
      if (res && res.code == 0) {
        const upgradeProgessData = res.data || [];
        for (let i = 0; i < upgradeProgessData.length; i++) {
          const itemProgessData = upgradeProgessData[i];
          //判断进度是否完成或者失败，成功或者失败就刷新列表
          if (
            ['complete', 'failed', 'timeout'].indexOf(itemProgessData.status) >
            -1
          ) {
            //当进度完成，出错或者超时时刷新列表
            this.getLogDetailList();
          } else {
            this.setTableUpgradeProgess(itemProgessData);
          }
        }
      }
    },
    /**
     * @description: 设置升级进度提示
     * @param {*} itemProgessData
     * @return {*}
     */
    setTableUpgradeProgess(itemProgessData) {
      // const statusMap = {
      //   parse: '检查参数',
      //   prepare: '探测本地储存空间',
      //   detect: '探测URL',
      //   retry: '下载重试',
      //   check: '校验',
      //   upgrade: '开始升级',
      //   complete: '升级成功！',
      //   failed: '升级失败！',
      //   timeout: '升级超时！',
      // };
      const upgradeLogId = itemProgessData.upgradeLogId;
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].id == upgradeLogId) {
          this.data[i].statusDesc = itemProgessData.desc;
          // if (itemProgessData.status == 'download') {
          //   // this.data[
          //   //   i
          //   // ].statusDesc = `版本下载完成 <span class='blue'>${this.formatdownLoadData(
          //   //   itemProgessData.downloadSize
          //   // )}/${this.formatdownLoadData(itemProgessData.totalSize)}M</span>`;
          //   this.data[
          //     i
          //   ].statusDesc = itemProgessData.desc
          // } else {
          //   if (
          //     ['complete', 'failed', 'timeout'].indexOf(
          //       itemProgessData.status
          //     ) > -1
          //   ) {
          //     this.getLogDetailList();
          //   } else {
          //     this.data[i].statusDesc =itemProgessData.desc
          //       //statusMap[itemProgessData.status] || '--';
          //   }
          // }
        }
      }
    },
    formatdownLoadData(data) {
      return (data / 1024 / 1024).toFixed(2);
    },
    //设备升级终止
    async abortJob(jobId) {
      const res = await requestHttp({
        api: `${maccApi.JOB_ABORT_POST_API}${jobId}`,
        method: 'POST',
        params: {},
      });
      if (res.code != 0) {
        this.$message.error(
          res.msg || this.$t('upgradeLog.deviceUpgradeStopFailed')
        );
      } else {
        this.$message.success(this.$t('upgradeLog.stopSucceeded'));
        this.getLogDetailList();
      }
    },

    //设备重新升级
    async restartJob(jobId) {
      const res = await requestHttp({
        api: `${maccApi.JOB_RESTART_POST_API}${jobId}`,
        method: 'POST',
        params: {},
      });
      if (res.code != 0) {
        this.$message.error(
          res.msg || this.$t('upgradeLog.deviceReupgradeFailed')
        );
      } else {
        this.$message.success(this.$t('upgradeLog.executeSuccess'));
        this.getLogDetailList();
      }
    },
    //返回设备升级日志URL
    callDetailLogurl() {
      let url = `?page=${this.detailparams.page}&per_page=${this.detailparams.per_page}`;
      if (this.detailparams.job_id) {
        url = url + '&job_id=' + this.detailparams.job_id;
      }
      if (this.detailparams.status) {
        url = url + '&status=' + encodeURI(this.detailparams.status);
      }
      if (this.detailparams.sn) {
        url = url + '&sn=' + this.detailparams.sn;
      }

      if (this.detailparams.groupName) {
        url = url + '&groupName=' + encodeURI(this.detailparams.groupName);
      }

      return url;
    },

    //切换升级状态
    LogDetailUpshot(status) {
      return this.statusMap[status] || '';
    },

    getVersion(str) {
      if (str == undefined) return '--';
      let index = str.indexOf(';');
      let result = '';
      if (index !== -1) {
        result = str.substring(0, index);
      } else {
        result = str;
      }
      return result;
    },

    //获取指定时间戳转化的时间
    getSpecifiedTime(date) {
      // let nowDate = new Date(date);
      // let year = nowDate.getFullYear();
      // let month =
      //   nowDate.getMonth() + 1 < 10
      //     ? '0' + (nowDate.getMonth() + 1)
      //     : nowDate.getMonth() + 1;
      // let day =
      //   nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate.getDate();
      // let hour =
      //   nowDate.getHours() < 10 ? '0' + nowDate.getHours() : nowDate.getHours(); // 获取时
      // let minutes =
      //   nowDate.getMinutes() < 10
      //     ? '0' + nowDate.getMinutes()
      //     : nowDate.getMinutes(); // 获取分
      // let seconds =
      //   nowDate.getSeconds() < 10
      //     ? '0' + nowDate.getSeconds()
      //     : nowDate.getSeconds(); // 获取秒
      // return (
      //   year +
      //   '-' +
      //   month +
      //   '-' +
      //   day +
      //   ' ' +
      //   hour +
      //   ':' +
      //   minutes +f
      //   ':' +
      //   seconds
      // );
      return moment(date).format('YYYY/MM/DD HH:mm:ss');
    },

    //将字符串转化为变量
    strChangeVariable(column, suffix) {
      return eval(`this.${column.dataIndex}${suffix}`);
    },

    //设备升级日志表格分页变化时触发
    handleTableDetailChange(pagination) {
      this.current = pagination.current;
      this.detailparams.page = pagination.current;
      this.detailparams.per_page = pagination.pageSize;
      this.getLogDetailList();
    },

    //刷新
    refeshTable() {
      this.getLogDetailList();
    },

    //表头列筛选
    onChange(e, confirm) {
      confirm();
      this.statusvalue = e.target.value;
      this.detailparams.status = e.target.value;
      this.inquireDetail();
    },

    //任务id输入框
    inputJobIdChange(e) {
      let val = e.target.value.replace(/[^\d]/g, '');
      this.taskId = val;
      this.detailparams.job_id = val;
    },

    //设备序列号输入框
    inputSnChange(e) {
      this.detailparams.sn = e.target.value;
    },
    //分组名称查询输入框
    inputGroupNameChange(e) {
      this.detailparams.groupName = e.target.value;
    },

    //查询
    inquireDetail() {
      this.current = 1;
      this.detailparams.page = 1;
      this.detailparams.per_page = 10;
      this.getLogDetailList();
    },

    //设备重新升级
    confirmRestart(recrod) {
      this.restartJob(recrod.upgradeJobId);
    },

    //设备升级终止
    confirmAbort(recrod) {
      this.abortJob(recrod.upgradeJobId);
    },
  },
};
</script>

<style lang="less" scoped>
.form-proup {
  line-height: 32px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
}

.panel-table {
  /deep/ .ant-table-thead > tr > th {
    padding: 5px 16px;
  }

  /deep/ .ant-table-tbody > tr > td {
    padding: 5px 16px;
  }

  .failure,
  .userabort,
  .abort {
    color: #de321f;
  }

  .executing {
    color: #2b6afd;
  }

  .offline {
    color: #f06f03;
  }
}

.statuStyle {
  background-color: #e2ebf0;
  min-width: 110px;
  padding: 10px;

  .ant-radio-group {
    display: flex;
    justify-content: flex-start;
    border-bottom: 1px solid #f0f2f5;
    line-height: 30px;
  }
}
</style>
<style>
.blue {
  color: #2b6afd;
}
</style>
